#pragma once
#define FILE_NAME "fifo"
#include<string>
#include<iostream>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#define PATH "."
#define NAME "fifo"
#define EXIT(m)        \
do \
{\
    perror(m);   \
    exit(EXIT_FAILURE);  \
}while(0)  
using namespace std;
class file
{
public:
    file(string path,string name)
    :_path(path)
    ,_name(name)
    {
        _filename = _path + "/" + _name;
    }
    void create()//创建命名管道
    {
        //设置权限掩码
        umask(0);
        //创建命名管道
        int n=mkfifo(_filename.c_str(),0666);
        if(n<0)
        {
            perror("mkfifo");
            exit(1);
        }
    }
    void openforwrite()//打开命名管道并且写入
    {
        int fd=open(_filename.c_str(),O_WRONLY);
        if (fd<0)
        {
            perror("open");
            exit(1);/* code */
        }
        string str;
        while(1)
        {
            cin >> str;
            int n = write(fd, str.c_str(), str.size());
            if (n == -1)
            {
                std::cerr << "write " << FILE_NAME << " failed" << std::endl;
            }
        }
        close(fd);
    }
    void openforread()//打开命名管道并且读取
    {
        int fd=open(_filename.c_str(),O_RDONLY);
        if(fd<0)
        {
            perror("open");
            exit(1);
        }
        char buf[1024];
        while(1)
        {
            int n=read(fd,buf,sizeof(buf));
            if(n>0)
            {
                cout<<buf<<endl;
            }
            else if(n==0)
            {
                cout<<"client quit"<<endl;
                break;
            }
            else
            {
                std::cerr << "read " << FILE_NAME << " failed" << std::endl;
            }
        }
    }
    ~file()
    {
        int n=unlink(_filename.c_str());
        if(n<0)
        {
            perror("unlink");
            exit(1);
        }
    }
private:
    string _path;
    string _name;
    string _filename;//由path和name构成

};